package iterable_i_iterator;

import java.util.*;

/**
 * Autor: Daniel Michalski
 * Data: 12.07.13
 */

public class FromTo implements Iterable<Calendar> {
    private Calendar from = Calendar.getInstance();
    private Calendar to = Calendar.getInstance();

    public FromTo(Calendar from, Calendar to) {
        this.from = from;
        this.to = to;
    }

    @Override
    public CalendarIterator iterator() {
        return new CalendarIterator();
    }

    private class CalendarIterator implements Iterator {
        Calendar current = Calendar.getInstance();
        Calendar next = Calendar.getInstance();

        private CalendarIterator() {
            current.setTime(from.getTime());
            current.add(Calendar.DATE, -1);
        }

        @Override
        public boolean hasNext() {
            next.setTime(current.getTime());
            next.add(Calendar.DATE, 1);
            return next.compareTo(to) <= 0;
        }

        @Override
        public Object next() {
            if (!hasNext())
                throw new NoSuchElementException();
            current.add(Calendar.DATE, 1);
            return current;
        }

        @Override
        public void remove() {}
    }
}
